package com.tbs.easyhomemoneyserver.dao.providers

import com.tbs.easyhomemoneyserver.utils.SysUtils.ColToString
import java.util.function.Function

class HomeMemberProvider {
    fun selectInRoles(homeId: Long, roles: Collection<String>): String {
        val inText = ColToString(roles, Function { s: String -> "'$s'" }, ",")

        val stringBuilder = StringBuilder(
            "\n" +
                    " SELECT * FROM (SELECT\n" +
                    "\thm.id AS id,\n" +
                    "\thm.home_id AS homeId,\n" +
                    "\thm.ENABLE AS enabled,\n" +
                    "\thm.member_type AS type,\n" +
                    "\thm.child_id AS userId,\n" +
                    "\tu.NAME AS userName \n" +
                    "FROM\n" +
                    "\tuser_rights ur\n" +
                    "\tLEFT JOIN api_rights ar ON ar.`role` IN ( " + inText + " ) \n" +
                    "\tAND ar.id = ur.rights_id\n" +
                    "\tLEFT JOIN user_right_param urp ON urp.user_right_id = ur.id\n" +
                    "\tLEFT JOIN home_member hm ON hm.child_id = ur.user_id \n" +
                    "\tAND hm.home_id = urp.number_value \n" +
                    "\tAND hm.home_id = '" + homeId + "' \n" +
                    "\tAND hm.`enable` = 1\n" +
                    "\tLEFT JOIN sys_user u ON u.id = hm.child_id \n" +
                    "WHERE\n" +
                    "\tar.id IS NOT NULL GROUP BY hm.id) l1 UNION ALL\n" +
                    "\t(\n" +
                    "\tSELECT\n" +
                    "\t\thm.id AS id,\n" +
                    "\t\thm.home_id AS homeId,\n" +
                    "\t\thm.ENABLE AS enabled,\n" +
                    "\t\thm.member_type AS type,\n" +
                    "\t\thm.child_id AS userId,\n" +
                    "\t\tu.NAME AS userName \n" +
                    "\tFROM\n" +
                    "\t\thome_member hm\n" +
                    "\t\tLEFT JOIN sys_user u ON u.id = hm.child_id \n" +
                    "\tWHERE\n" +
                    "\t\thm.home_id = '" + homeId + "' \n" +
                    "\t\tAND hm.member_type = '0' \n" +
                    "\t)\n"
        )

        return stringBuilder.toString()
    }
}
